<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <link rel="stylesheet" href="../../lib/yzhUpload/control/css/zyUpload.css" type="text/css">

    <style>
        body {
            background-color: #ffffff;
        }

        .aui-upload-box {
            background-color: #fff;
            width: 105px;
            height: 105px;
            padding-top: 5px;
            padding-right: 5px;
        }

        .chose_pic_btn {
            width: 95px;
            height: 95px;
            position: relative;
            display: inline-block;
            background-image: url('');
            box-sizing: border-box;
            background-size: 45px 45px;
            background-position: center center;
            background-repeat: no-repeat;
            background-color: #ededed;
            margin-left: 3.3333%;
            margin-bottom: 12px;
            border-radius: 5px;
        }

        .chose_pic_btn div {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
        }

    </style>
</head>
<body>
<div class="layui-form layuimini-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">标题</label>
        <div class="layui-input-block">
            <input type="text" name="title" lay-verify="required" lay-reqtext="标题不能为空" placeholder="请填写标题" value=""
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label required">缩略图</label>
        <div class="layui-input-block">
            <div class="layui-upload">
                <div class="aui-upload-box" onclick="addPic()">
                    <div class="aui-upload-pic">
					<span class="chose_pic_btn" id="mainDiagram">
						<div>
                        </div>
					</span>
                    </div>
                </div>
                <p id="errText"></p>
                <button type="button" class="layui-btn" id="upload-mainDiagram">上传图片</button>
            </div>
            <input type="text" style="display: none" name="image" lay-verify="required" lay-reqtext="缩略图不能为空"
                   value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">文章地址</label>
        <div class="layui-input-block">
            <input type="text" name="url" placeholder="请填写跳转地址" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">自定义内容</label>
        <div class="layui-input-block">
            <div id="editor" style="margin: 5px 0 5px 0"></div>
            <button class="layui-btn layui-btn-danger" onclick="emptyDetails()">清空内容</button>
            <input type="text" name="content" value="" style="display: none" placeholder="请填写内容">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认提交</button>
        </div>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>

<script>

    let editor;
    window.onload = function () {

        layui.use(['layer', 'form'], function () {
            var form = layui.form,
                layer = layui.layer,
                $ = layui.$;

            // 监听提交
            form.on('submit(saveBtn)', function (data) {

                var index = layer.alert("确定提交吗？", {
                    title: '提示'
                }, function () {
                    let myMsg = layer.msg("正在保存...", {
                        icon: 16,
                        time: -1
                    })
                    $.ajax({
                        type: "post",
                        url: '/journalism//article/add',
                        data: JSON.stringify(data.field),
                        dataType: 'json',
                        contentType: 'application/json; charset=UTF-8',
                        success: function (req) {
                            layer.msg(req.msg);
                            layer.close(index);
                            // 关闭弹出层
                            setTimeout(function () {
                                layer.close(myMsg);// 手动关闭
                                location.reload();// 刷新页面
                                let iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                                // 调用父页面的方法
                                let parentWindow = window.parent;
                                parentWindow.reloadTable();
                            }, 1500);
                        },
                        error: function (e) {
                            layer.msg(req.msg);
                            layer.close(myMsg);//手动关闭
                        }
                    })

                });

                return false;
            });

        });

        //常规使用 - 普通图片上传
        layui.use(['layer'], function () {
            var upload = layui.upload,
                $ = layui.$;
            let uploadInst = upload.render({
                elem: '#upload-mainDiagram'
                , url: '/meily/upload'
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#mainDiagram').css({
                            'background-image': 'url(' + result + ')',
                            'background-size': '100% 100%'
                        }); //图片链接（base64）
                    });
                    layer.msg('上传中', {icon: 16, time: 0});
                }
                , done: function (res) {
                    //如果上传失败
                    if (res.code !== '200') {
                        return layer.msg('上传失败');
                    }
                    //上传成功的一些操作
                    $('input[name="image"]').val(res.url);
                    $('#errText').html(''); //置空上传失败的状态
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#errText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs upload-reload" style="margin-bottom: 5px">重试</a>');
                    demoText.find('.upload-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
                //进度条
                , progress: function (n, elem, e) {
                    if (n == 100) {
                        layer.msg('上传完毕', {icon: 1});
                    }
                }
            });
        });

        // 富文本编辑器
        layui.use(['layer', 'wangEditor'], function () {
            var $ = layui.jquery,
                layer = layui.layer,
                wangEditor = layui.wangEditor;

            editor = new wangEditor('#editor');
            editor.customConfig.uploadImgServer = "/meily/upload";
            editor.customConfig.uploadFileName = 'file';
            editor.customConfig.pasteFilterStyle = false;
            editor.customConfig.uploadImgMaxLength = 5;
            editor.customConfig.uploadImgHooks = {
                // 上传超时
                timeout: function (xhr, editor) {
                    layer.msg('上传超时！')
                },
                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                customInsert: function (insertImg, result, editor) {
                    console.log(result);
                    if (result.code == 200) {
                        var url = result.url;
                        insertImg(url);
                        // url.forEach(function (e) {
                        //     insertImg(e);
                        // })
                    } else {
                        layer.msg(result.msg);
                    }
                }
            };
            editor.customConfig.customAlert = function (info) {
                layer.msg(info);
            };
            editor.customConfig.onchange = function (html) {
                $('input[name="content"]').val(html);
            };
            editor.create();
        });
    }

    /**
     * 清空内容（包括源代码）
     */
    function emptyDetails() {
        editor.txt.clear();
        $('input[name="content"]').val('');
        layui.use(['layer'], function () {
            let $ = layui.$, layer = layui.layer;
            layer.msg("已清除！")
        })
    }

    /**
     * 添加商品主图
     */
    function addPic() {
        layui.use(['layer', 'form'], function () {
            const layer = layui.layer
            layer.prompt({
                title: '请输入图片链接',
                btn: ['确定', '取消'],
                area: ['200px', '20px'],
                formType: 0
            }, function (text, index) {
                if (isNotNull(text)) {
                    $('#mainDiagram').css({
                        'background-image': 'url(' + text + ')',
                        'background-size': '100% 100%'
                    }); //图片链接（base64）
                    $('input[name="image"]').val(text);
                } else {
                    layer.msg("图片链接不能为空噢");
                }
                layer.close(index);
            });
        });
    }

</script>
</body>
</html>
